package algorithm;

class myAtoi {
    public static int myAtoi(String s) {
        int sign = 1;
        int res = 0;
        int n = s.length();
        int i = 0;
        //去除空格
        while(i < n && s.charAt(i) == ' '){
            i++;
        }
        int start = i;
        for(;i < n; i++){
            char c = s.charAt(i);
            if(c == '-' && i == start){
                sign = -1;
            }
            else if(c == '+' && i == start){
                sign = 1;
            }
            else if(Character.isDigit(c)){
                int t = c - '0';
                //加前先判断是否溢出
                if(res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && t > Integer.MAX_VALUE % 10)){
                    return Integer.MAX_VALUE;
                }
                if(res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && -t < Integer.MIN_VALUE % 10)){
                    return Integer.MIN_VALUE;
                }
                res = res * 10 + t * sign;
            }else break;
        }
        return res;
    }

    public static void main(String[] args) {
        String str = "-2147483647";
        System.out.println(myAtoi.myAtoi(str));

    }
}